package com.augurit.wf.common.listener;

import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.ApplicationContext;
import org.springside.modules.utils.SpringContextHolder;
import com.augurit.wf.bi.web.form.WfActElemPrivDefForm;


/**
 * 工作流引擎初始化监听器
 *
 */
@Configurable("wfInitListener")
public class WfInitListener implements ServletContextListener {
	public static final String PRIV_CACHE = "priv_cache";		//工作流权限控制缓存信息
	
	private static final int EXPECT_PRIV_CACHE_SIZE = 2000;		//预计权限缓存大小 
	private static final int INIT_CACHE_SIZE = 3000; 			//初始权限缓存大小
	private static final float LOAD_FACTOR = 0.75f;				//加载因子
	
	public void contextDestroyed(ServletContextEvent sce) {
		// TODO Auto-generated method stub
	}

	public void contextInitialized(ServletContextEvent sce) {
		// Web上下文
		ServletContext servletContext = sce.getServletContext();
		
		// 加载Spring配置文件
		ApplicationContext applicationContext = SpringContextHolder.getApplicationContext();
		
		//加载流程结点的权限配置
		loadWfProcActPrivDef(servletContext, applicationContext);
	}
	
	/**
	 * 加载系统中所有流程结点对应权限配置信息
	 * @param servletContext
	 * @param applicationContext
	 */
	public  void loadWfProcActPrivDef(ServletContext servletContext, ApplicationContext applicationContext){
		System.out.println("正在初始化流程结点的权限缓存空间，请稍候 ...... ");
		
		@SuppressWarnings("serial")
		Map<String, WfActElemPrivDefForm> map = Collections.synchronizedMap(new LinkedHashMap<String, WfActElemPrivDefForm>(INIT_CACHE_SIZE, LOAD_FACTOR, true){
			protected boolean removeEldestEntry(Map.Entry<String, WfActElemPrivDefForm> eldest){
				return size() > EXPECT_PRIV_CACHE_SIZE;
			}
		});
		
		if(map != null){
			servletContext.setAttribute(PRIV_CACHE, map);
			System.out.println("加载初始化流程结点的权限缓存空间完毕");
		}
		else{
			throw new RuntimeException("初始化流程结点的权限缓存空间失败");
		}
		
		
	}

}
